package graphics.pattern 
{
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.Shape;
	import flash.geom.ColorTransform;
	import flash.geom.Point;
	import shapes.shapes2D.distribution.random.PRNG;
	/**
	 * @author Nicolas Barradeau
	 * http://en.nicoptere.net
	 */
	public class Hachage 
	{
		
		static private var canvas:Shape = new Shape();
		
		public function Hachage(){}
		
		/**
		 * @param	bd target bitmapData
		 * @param	iterations iteration count
		 * @param	colorFunction a closure that returns a  uint
		 */
		static public function process( bd:BitmapData, iterations:int = 100, colorFunction:Function = null ):void
		{
			
			if ( colorFunction == null ) colorFunction = getColor;
			
			
			var p0:Point = new Point(); 
			var p1:Point = new Point(); 
			var p2:Point = new Point(); 
			
			
			var angle:Number;
			var radX:Number = bd.width * Math.SQRT2;
			var radY:Number = bd.height * Math.SQRT2;
			var c:Point = new Point( radX * .5, radY * .5 );
			var ct:ColorTransform = new ColorTransform( 1, 1, 1, 1, 0, 0, 0, -128 );
			
			var i:int;
			for ( i = 0; i < iterations; i++ )
			{
				
				
				angle = Math.PI * 2 * PRNG.random();
				p0.x = c.x + Math.cos( angle ) * radX;
				p0.y = c.y + Math.sin( angle ) * radY;
				
				angle = Math.PI * 2 * PRNG.random();
				p1.x = c.x + Math.cos( angle ) * radX;
				p1.y = c.y + Math.sin( angle ) * radY;
				
				angle = Math.PI * 2 * PRNG.random();
				p2.x = c.x + Math.cos( angle ) * radX;
				p2.y = c.y + Math.sin( angle ) * radY;
				
				canvas.graphics.clear();
				canvas.graphics.beginFill( colorFunction() );
				
				canvas.graphics.moveTo( p0.x, p0.y );
				canvas.graphics.lineTo( p1.x, p1.y );
				canvas.graphics.lineTo( p2.x, p2.y );
				canvas.graphics.lineTo( p0.x, p0.y );
				
				canvas.graphics.endFill();
				
				bd.draw( canvas, null, ct );
				
				bd.threshold( bd, bd.rect, new Point( 0,0 ), '>=', 0xFE << 24 | 0, 0 );
				
			}
			
		}
		
		static private function getColor():uint 
		{
			return 0xFFFFFF;
		}
	}

}